package inet.app.vod.dialog;

import inet.app.vod.activity.R;
import inet.app.vod.adapter.MySpinnerAdapter;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class MySpinnerDialogFragment extends DialogFragment {

	String mTitle;
	String[] mObjects;
	SpinnerListener mListener;
	MySpinnerAdapter mAdapter;
	int mCurPosition;

	public static MySpinnerDialogFragment newInstance(String title,
			String[] objects) {
		Bundle bundle = new Bundle();
		bundle.putString("title", title);
		bundle.putStringArray("objects", objects);
		MySpinnerDialogFragment dialog = new MySpinnerDialogFragment();
		dialog.setArguments(bundle);
		return dialog;
	}

	public void setSpinnerListener(SpinnerListener listener) {
		this.mListener = listener;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		Bundle bundle = this.getArguments();
		if (bundle != null) {
			this.mTitle = bundle.getString("title");
			this.mObjects = bundle.getStringArray("objects");
		}

		Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setCancelable(true);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.dialog_spinner, null);
		TextView title = (TextView) view.findViewById(R.id.title_text);
		title.setText(TextUtils.isEmpty(mTitle) ? "" : mTitle);

		ListView listView = (ListView) view.findViewById(R.id.spinner_list);
		mAdapter = new MySpinnerAdapter(getActivity(), 0, mObjects);
		mAdapter.update(mCurPosition);
		listView.setAdapter(mAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (null != mListener) {
					mAdapter.update(position);
					mListener.onItemClick(parent, view, position, id);
				}
			}
		});
		dialog.setContentView(view);

		return dialog;
	}

	public void setCurPosition(int position) {
		mCurPosition = position;
	}

	public interface SpinnerListener {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id);
	}

}